//
//  PublicCourse.m
//  Courses
//
//  Created by xxx on 15/1/6.
//  Copyright (c) 2015年 wtf. All rights reserved.
//

#import "PublicCourse.h"
#import "Request.h"

@implementation PublicCourse

- (id)initWithJsonDict:(NSDictionary *)jsonDict
{
    if (self = [super initWithJsonDict:jsonDict])
    {
        self.markTime = jsonDict[@"markTime"];
    }
    return self;
}

+ (NSArray *)publicCourses
{
    NSMutableArray *publicCourses = [[NSMutableArray alloc] init];
    
    Request *request = [Request requestWithName:@"get_open_courses"];
    
//    "condition":{                 //过滤条件
//        "TeacherId": "讲师id",
//        "tagId":"知识点id"
//    },
//    "sort": 1,     // 排序方式, 1: 按更新时间, 2: 观看量, 3: 收藏数
//    "page":{
//        "pageNo": 1,
//        "pageSize": 20

    request.body[@"sort"] = [NSString stringWithFormat:@"%d", 1];
    
    Response *res = [request response];
    if (!res.result)
    {
        return [publicCourses copy];
    }
    
    for (id courseJson in res.content[@"courses"])
    {
        PublicCourse *course = [[self alloc] initWithJsonDict:courseJson];
        [publicCourses addObject:course];
    }
    
    return [publicCourses copy];
}

+ (NSArray *)publicCoursesWithSortOption:(NSInteger)sortOption
                               teacherId:(NSString *)teacherId
                                   tagId:(NSString *)tagId
                                  pageNo:(NSInteger)pageNo
{
    NSMutableArray *publicCourses = [[NSMutableArray alloc] init];
    
    Request *request = [Request requestWithName:@"get_open_courses"];
    
    request.body[@"sort"] = [NSNumber numberWithInt:sortOption];
//    request.body[@"TeacherId"] = [NSString stringWithString:teacherId];
    NSMutableDictionary *condition = [[NSMutableDictionary alloc] init];
    if (teacherId.length)
        condition[@"teacherId"] = teacherId;
    if (tagId.length)
        condition[@"tagId"] = tagId;
    request.body[@"condition"] = condition;
    
    NSMutableDictionary *page = [[NSMutableDictionary alloc] init];
    page[@"pageNo"] = [NSNumber numberWithInt:pageNo];
    page[@"pageSize"] = [NSNumber numberWithInt:20];
    request.body[@"page"] = page;
    
    Response *res = [request response];
    if (!res.result)
    {
        return [publicCourses copy];
    }
    
    for (id courseJson in res.content[@"courses"])
    {
        PublicCourse *course = [[self alloc] initWithJsonDict:courseJson];
        [publicCourses addObject:course];
    }
    
    return [publicCourses copy];
}

+ (BOOL)markPublicCourseById:(NSString *)courseId
{
    Request *request = [Request requestWithName:@"mark_courses"];
    request.body[@"courseId"] = courseId;
    return [request response].result;
}

+ (BOOL)downloadPublicCourseById:(NSString *)courseId
{
    Request *request = [Request requestWithName:@"download_courses"];
    request.body[@"courseId"] = courseId;
    return [request response].result;
}

@end
